package core.modelManager
{
	import com.hydrotik.queueloader.QueueLoader;
	import com.hydrotik.queueloader.QueueLoaderEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	
	import memory.MemoryRecovery;
	
	import structure.DualMap;
	[Event(name="complete", type="flash.events.Event")]
	[Event(name="progress", type="flash.events.ProgressEvent")]
	/**
	 * 通过init函数，传数组进行初始化，数组的格式为[{key,path},{key,path}.....]
	 * xml数据采用bulkloader进行加载
	 */ 
	public class ModelManager extends EventDispatcher implements IModelManager
	{
		private static var _instance:ModelManager;
		private var loader:QueueLoader=new QueueLoader();
		private var map:DualMap=new DualMap();
		private var xmls:Object=new Object();
		public function ModelManager()
		{
			if(_instance==null)
			{
				super();
				_instance=this;
			}else
			{
				throw new Error("ModelManager不能被实例化");
			}
		}
		public static function getInstance():ModelManager
		{
			if(_instance==null)
			{
				_instance=new ModelManager();
			}
			return _instance;
		}
		/**
		 * 初始化
		 */ 
		public function init(array:Array,withProgress:Boolean):void
		{
			for each(var obj:Object in array)
			{
				loader.addItem(obj.path);
				map.put(obj.key,obj.path);
			}
			loader.execute();
			loader.addEventListener(QueueLoaderEvent.QUEUE_COMPLETE,on_all_loaded);
			loader.addEventListener(QueueLoaderEvent.ITEM_COMPLETE,on_item_loaded);
//			if(withProgress) loader.addEventListener(QueueLoaderEvent.QUEUE_PROGRESS,on_progress_refresh);
		}
		/**
		 * queueloader加载完某个数据库
		 */ 
		private function on_item_loaded(e:QueueLoaderEvent):void
		{
			xmls[map.getKey(e.path.url)]=e.content;
		}
		/**
		 * queueloader加载完全部数据库
		 */ 
		private function on_all_loaded(e:QueueLoaderEvent):void
		{
			dispatchEvent(new Event(Event.COMPLETE));
			MemoryRecovery.getInstance().gcFun(loader,QueueLoaderEvent.QUEUE_COMPLETE,on_all_loaded);
			MemoryRecovery.getInstance().gcFun(loader,QueueLoaderEvent.ITEM_COMPLETE,on_item_loaded);
			MemoryRecovery.getInstance().gcFun(loader,QueueLoaderEvent.QUEUE_PROGRESS,on_progress_refresh);
			loader.dispose();
			loader=null;
			map=null;
		}
		/**
		 * 时刻更新加载进度
		 */ 
		private function on_progress_refresh(e:QueueLoaderEvent):void
		{
			var event:ProgressEvent=new ProgressEvent(ProgressEvent.PROGRESS);
			event.bytesLoaded=e.bytesLoaded;
			event.bytesTotal=e.bytesTotal;
			dispatchEvent(event);
		}
		/**
		 * 获取指定的数据库
		 */ 
		public function getXml(key:String):XML
		{
			return xmls[key];
		}
	}
}